Overview
The AuthController handles user authentication, session management, and role-based redirects. It validates credentials, manages login/logout operations, and routes users to appropriate dashboards based on their access level (grado).
Source: controllers/AuthController.php
Dependencies:
Models/AuthModel.php - User authentication data access
PHP Sessions - Session management
Constructor
public function __construct ()
Initializes the controller by starting a PHP session (if not already active) and instantiating the AuthModel.
Sessions are automatically started if session_status() === PHP_SESSION_NONE
Methods
index()
public function index () : void
Displays the login page. If the user is already authenticated (has active session), redirects them to their role-appropriate dashboard.
Behavior:
Checks for $_SESSION['logged_in']
If authenticated: calls redirigirSegunGrado() with user’s grade
If not authenticated: loads Views/auth/login.php
Session Variables Used:
Indicates if user has authenticated successfully
User’s access level (1=Admin, 2=Auxiliary, 3=Consulta)
Example Usage:
GET index.php?url=auth/index
login()
public function login () : void
Authenticates user credentials via POST request and establishes session on success.
HTTP Method: POST
POST Parameters:
User’s login username (trimmed)
User’s plain-text password
Response: JSON
true if authentication succeeded, false otherwise
URL to redirect user to on success (role-based)
Error message if authentication failed
Session Variables Set on Success:
$_SESSION [ 'user' ] = $user [ 'USR' ]; // Username
$_SESSION [ 'nombre' ] = $user [ 'NOMBRE' ]; // Full name
$_SESSION [ 'grado' ] = $user [ 'GRADO' ]; // Access level
$_SESSION [ 'logged_in' ] = true ; // Auth flag
$_SESSION [ 'last_activity' ] = time (); // Timestamp
Security Features:
Session regeneration with session_regenerate_id(true) after successful login
Plain-text password comparison: $password === $user['PAS']
The system currently uses plain-text password storage. For production environments, implement password hashing using password_hash() and password_verify().
Success Response Example:
{
"success" : true ,
"redirect" : "index.php?url=home/index"
}
Error Response Example:
{
"success" : false ,
"message" : "Credenciales incorrectas"
}
Source Code:
public function login () {
header ( 'Content-Type: application/json' );
if ( $_SERVER [ 'REQUEST_METHOD' ] === 'POST' ) {
$username = trim ( $_POST [ 'username' ] ?? '' );
$password = $_POST [ 'password' ] ?? '' ;
$user = $this -> model -> buscarUsuario ( $username );
if ( $user && $password === $user [ 'PAS' ]) {
$_SESSION [ 'user' ] = $user [ 'USR' ];
$_SESSION [ 'nombre' ] = $user [ 'NOMBRE' ];
$_SESSION [ 'grado' ] = $user [ 'GRADO' ];
$_SESSION [ 'logged_in' ] = true ;
$_SESSION [ 'last_activity' ] = time ();
session_regenerate_id ( true );
echo json_encode ([
'success' => true ,
'redirect' => $this -> getRedirectUrl ( $user [ 'GRADO' ])
]);
} else {
echo json_encode ([ 'success' => false , 'message' => 'Credenciales incorrectas' ]);
}
}
}
logout()
public function logout () : void
Destroys the user’s session and redirects to the login page.
Behavior:
Unsets all session variables with session_unset()
Destroys the session with session_destroy()
Redirects to index.php?url=auth/index
Example Usage:
GET index.php?url=auth/logout
Source Code:
public function logout () {
session_unset ();
session_destroy ();
header ( 'Location: index.php?url=auth/index' );
exit ;
}
getRedirectUrl()
private function getRedirectUrl ( int $grado ) : string
Determines the appropriate redirect URL based on user’s access level (grado).
Parameters:
User’s access level:
1 = Administrator
2 = Auxiliary staff
3 = Consulta (view-only)
Return Value:
URL string for role-based redirect
Redirect Mapping:
Grado Role Redirect URL 1 Administrator index.php?url=home/index2 Auxiliary index.php?url=devolucion/crear3 Consulta index.php?url=consulta/indexdefault Unknown index.php?url=auth/index
Source Code:
private function getRedirectUrl ( $grado ) {
switch ( $grado ) {
case 1 :
return 'index.php?url=home/index' ;
case 2 :
return 'index.php?url=devolucion/crear' ;
case 3 :
return 'index.php?url=consulta/index' ;
default :
return 'index.php?url=auth/index' ;
}
}
redirigirSegunGrado()
private function redirigirSegunGrado ( int $grado ) : void
Performs HTTP redirect based on user’s access level.
Parameters:
User’s access level (1, 2, or 3)
Behavior:
Calls getRedirectUrl($grado) to determine target URL
Sends Location header
Exits script execution
Source Code:
private function redirigirSegunGrado ( $grado ) {
header ( 'Location: ' . $this -> getRedirectUrl ( $grado ));
exit ;
}
Authentication Flow
Complete Authentication Sequence
User visits site → index.php?url=auth/index
AuthController::index() checks for existing session
If not logged in → displays login form
User submits credentials → POST to index.php?url=auth/login
AuthController::login() validates credentials with AuthModel
On success:
Session variables set
Session ID regenerated
JSON response with redirect URL
Frontend redirects user to role-appropriate dashboard
User logs out → index.php?url=auth/logout
Session destroyed → redirected to login
Security Considerations
Critical Security Issues:
Plain-text passwords - Passwords are stored and compared in plain text
No rate limiting - Brute force attacks are not mitigated
No CSRF protection - Cross-site request forgery tokens not implemented
No password complexity - No validation rules enforced
Recommended Improvements:
Implement password_hash() and password_verify() for password storage
Add rate limiting for login attempts
Implement CSRF tokens for login form
Add session timeout checks using last_activity
Use HTTPS for all authentication endpoints
Usage Example
JavaScript Login Implementation
// Login form submission
const form = document . getElementById ( 'loginForm' );
form . addEventListener ( 'submit' , async ( e ) => {
e . preventDefault ();
const formData = new FormData ( form );
try {
const response = await fetch ( 'index.php?url=auth/login' , {
method: 'POST' ,
body: formData
});
const data = await response . json ();
if ( data . success ) {
window . location . href = data . redirect ;
} else {
alert ( data . message );
}
} catch ( error ) {
console . error ( 'Login error:' , error );
}
});
PHP Session Check
// Check if user is authenticated
if ( ! isset ( $_SESSION [ 'logged_in' ]) || ! $_SESSION [ 'logged_in' ]) {
header ( 'Location: index.php?url=auth/index' );
exit ;
}
// Check user role
if ( $_SESSION [ 'grado' ] != 1 ) {
die ( 'Access denied: Administrator privileges required' );
}